<template>
  <div class="container">
    <div class="mainConBox">
      <div class="filterBox">
        <el-row class="searchInputWidth">
          <el-form
            :inline="true"
            :model="filterField"
            ref="formData"
            :rules="rules"
          >
            <div class="baseSearch">
              <div class="baseSearchTitle">统计时段</div>
              <div class="baseSearchBox">
                <el-form-item
                  label=""
                  class="row-padding-bottom"
                  prop="queryStartDate"
                >
                  <el-date-picker
                    v-model="filterField.queryStartDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                  >
                  </el-date-picker>
                </el-form-item>
                <span style="display: inline-block; margin-top: 8px">至</span>
                <el-form-item
                  label=""
                  class="row-padding-bottom"
                  prop="queryEndDate"
                >
                  <el-date-picker
                    v-model="filterField.queryEndDate"
                    type="date"
                    value-format="yyyy-MM-dd"
                    :picker-options="pickerOptions"
                  >
                  </el-date-picker>
                </el-form-item>
              </div>
              <div class="baseSearchTitle">筛选项目</div>
              <div class="baseSearchBox">
                <el-form-item label="" class="row-padding-bottom">
                  <el-cascader
                    ref="manageArea"
                    v-model="areaId"
                    :options="areasOptions"
                    @change="getAreaId"
                    clearable
                    filterable
                    :props="{ checkStrictly: true }"
                    placeholder="请选择区域"
                  ></el-cascader>
                </el-form-item>
                <el-form-item label="" class="row-padding-bottom">
                  <el-select
                    class="selectWidth"
                    v-model="filterField.industryId"
                    filterable
                    placeholder="请选择行业"
                    clearable
                  >
                    <el-option
                      v-for="item in industryOptions"
                      :key="item.code"
                      :label="item.name"
                      :value="item.code"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" class="row-padding-bottom">
                  <el-select
                    placeholder="请选择投资类别"
                    v-model="filterField.investment"
                    class="baseSearchItem"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in investmentOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" class="row-padding-bottom">
                  <el-select
                    v-model="filterField.status"
                    class="baseSearchItem"
                    placeholder="请选择开工状态"
                    clearable
                    filterable
                  >
                    <el-option
                      v-for="item in statusOptions"
                      :key="item.id"
                      :label="item.name"
                      :value="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="" class="row-padding-bottom">
                  <el-input
                    v-model="filterField.projectName"
                    placeholder="请输入项目名称"
                    clearable
                  ></el-input>
                </el-form-item>
                <el-form-item class="searchBut">
                  <el-button
                    type="primary"
                    icon="icon iconfont iconchazhao1"
                    @click="searchList"
                    class="searchBtn"
                  >
                    <span>搜索</span>
                  </el-button>
                </el-form-item>
              </div>
            </div>
          </el-form>
        </el-row>
      </div>
      <div class="spacing"></div>
      <div class="tableBox">
        <el-row class="tableBoxTip">
          <el-col :span="18">筛选出来的项目在时段内产生的数据</el-col>
          <el-col :span="6" style="text-align: right">
            <colSetup
              :tableColList="colSetupTableCol"
              @getSelectMenuId="getSelectMenuIds"
            />
            <el-button
              class="commonBut saveBtn funComBut"
              icon="icon iconfont icondaochu"
              @click="toExportExcel"
              style="margin-left: 10px"
            >
              <span class="opetareText">导出报表</span>
            </el-button>
          </el-col>
        </el-row>
        <el-table
          :data="tableList"
          v-loading="loading"
          :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
          highlight-current-row
          stripe
          ref="table"
          style="border: 1px solid #dfe6ec"
          :max-height="tableHeight"
          @sort-change="sortChange"
        >
          <my-column
            v-for="(item, index) in tableColOne"
            :key="index"
            :col="item"
            :sortable="
              [
                'createTime',
                'startDate',
                'cycle',
                'realNameTotal',
                'attTotal',
                'salaryAllIn',
                'saAll',
                'psTotal',
              ].includes(item.prop)
                ? 'custom'
                : false
            "
          ></my-column>
        </el-table>
      </div>
      <div class="tablePage">
        <Pagination
          ref="pagination"
          @getList="getTableList"
          :filterField="filterField"
          :requestUrl="requestUrl"
        ></Pagination>
      </div>
      <el-dialog
        title="正在生成数据，请稍后"
        :visible.sync="dialogVisible"
        width="400px"
        :close-on-click-modal="false"
        :show-close="false"
        class="loadData"
      >
        <el-progress
          :percentage="percentage"
          :color="customColor"
          :show-text="false"
        ></el-progress>
      </el-dialog>
    </div>
  </div>
</template>
<script>
import common from '../../kits/common'
import MyColumn from './MyColumn'

import { mapState, mapActions } from 'vuex'
export default {
  components: { MyColumn },
  name: 'projectGeneratedData',
  data() {
    var checkStartMonth = (rule, value, callback) => {
      if (value) {
        let start = value
        let end = this.filterField.queryEndDate
        const day = 365 * 24 * 3600 * 1000
        const startTime = new Date(start).getTime()
        const endTime = new Date(end).getTime()
        if (start && end) {
          if (start > end) {
            callback(new Error('开始日期不能大于结束日期'))
          } else if (endTime - startTime > day) {
            callback(new Error('统计时段最多可查365天'))
          } else {
            this.$refs.formData.clearValidate('queryEndDate')
            callback()
          }
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择统计时段'))
      }
    }
    var checkEndMonth = (rule, value, callback) => {
      if (value) {
        let start = this.filterField.queryStartDate
        let end = value
        const day = 365 * 24 * 3600 * 1000
        const startTime = new Date(start).getTime()
        const endTime = new Date(end).getTime()
        if (start && end) {
          if (start > end) {
            callback(new Error('开始日期不能大于结束日期'))
          } else if (endTime - startTime > day) {
            callback(new Error('统计时段最多可查365天'))
          } else {
            this.$refs.formData.clearValidate('queryStartDate')
            callback()
          }
        } else {
          callback()
        }
      } else {
        callback(new Error('请选择统计时段'))
      }
    }
    return {
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now() //如果没有后面的-8.64e7就是不可以选择今天的
        },
      },
      showExcel: false,
      headerList: [], //列表头部数据
      tableList: [], //列表数据
      filterField: {
        areaId: '',
        industryId: '',
        status: '',
        investment: '',
        // createDateStart: "",
        // createDateEnd: "",
        // startDateStart: "",
        // startDateEnd: "",
        projectName: '',
        queryStartDate: '',
        queryEndDate: '',
      },
      startTimeTitleTwo: '开工开始日期',
      endTimeTitleTwo: '开工结束日期',
      requestUrl: 'api-s/cs/stats/projectperiod/listbypage',
      areaId: '', //区域
      tableHeight: null,
      dialogVisible: false,
      percentage: 0,
      startPro: 0,
      colSetupTableCol: [],
      tableCol: [],
      tableColOne: [],
      selectProps: [],
      mark: 'projectDetailReport',
      rules: {
        queryStartDate: [
          { required: true, validator: checkStartMonth, trigger: 'blur' },
        ],
        queryEndDate: [
          { required: true, validator: checkEndMonth, trigger: 'blur' },
        ],
      },
    }
  },
  computed: {
    ...mapState([
      'investmentOptions',
      'statusOptions',
      'areasOptions',
      'industryOptions',
    ]),
  },
  created() {
    this.getStatus({})
    this.getAreas({ areaId: this.$store.state.areaInfoArr.areaId })
    this.getIndustry({})
    let newDate = ''
    let curMonth = new Date().getMonth() + 1
    let curYear = new Date().getFullYear()
    let curDay = new Date().getDate() - 1
    newDate = curYear + '-' + curMonth + '-' + curDay
    this.filterField.queryStartDate = newDate
    this.filterField.queryEndDate = newDate
    this.$nextTick(function () {
      this.$refs.pagination.getTableListData()
      this.getTableHeaderF()
    })
  },
  mounted() {
    this.loading = true
    this.$nextTick(function () {
      this.tableHeight = window.innerHeight - 300
      // 监听窗口大小变化
      let self = this
      window.onresize = function () {
        self.tableHeight = window.innerHeight - 300
      }
    })
  },
  methods: {
    ...mapActions([
      'getInvestmenttype',
      'getStatus',
      'getAreas',
      'getIndustry',
    ]),
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValue(val) {
      if (val) {
        this.filterField.createDateStart = val
      } else {
        this.filterField.createDateStart = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValue(val) {
      if (val) {
        this.filterField.createDateEnd = val
      } else {
        this.filterField.createDateEnd = ''
      }
    },
    /**
     * @description: 获取开始日期
     * @param {*} urls
     * @param {*} datas
     */
    getStartTimeValueTwo(val) {
      if (val) {
        this.filterField.startDateStart = val
      } else {
        this.filterField.startDateStart = ''
      }
    },
    /**
     * @description: 获取结束日期
     * @param {*} urls
     * @param {*} datas
     */
    getEndTimeValueTwo(val) {
      if (val) {
        this.filterField.startDateEnd = val
      } else {
        this.filterField.startDateEnd = ''
      }
    },

    //获取选中的区域最后一级id
    getAreaId(val) {
      var areaId = this.areaId[this.areaId.length - 1]
      if (val.length > 0) {
        this.filterField.areaId = areaId
      } else {
        this.filterField.areaId = ' '
      }
    },
    searchList(val) {
      this.$refs['formData'].validate((valid) => {
        if (valid) {
          this.dialogVisible = true
          this.percentage = 0
          let that = this
          this.startPro = setInterval(function () {
            that.percentage += 30
            if (that.percentage > 70) {
              clearInterval(that.startPro)
              that.$nextTick(function () {
                that.$refs.pagination.getTableListData()
              })
            }
          }, 50)
        } else {
          return false
        }
      })
    },
    getSelectMenuIds(val, allVal) {
      this.tableColOne = []
      val.forEach((item) => {
        this.tableColOne.push(...item.children)
      })
      this.filterField.sortField = ''
      this.filterField.sort = ''
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
    },
    getTableList(data) {
      this.percentage = 100
      let that = this
      setTimeout(function () {
        that.dialogVisible = false
      }, 200)
      this.tableList = data
      this.$nextTick(() => {
        this.$refs.table.doLayout()
      })
      this.loading = false
      if (this.tableList.length < 1) {
        this.isEmpty = true
      }
    },
    //获取表头
    getTableHeaderF() {
      this.axios
        .post('/api-s/dimension/head', { type: 'PROJECT_PERIOD', complex: 1 })
        .then((res) => {
          if (!res.data.hasError) {
            let datas = JSON.parse(JSON.stringify(res.data.result))
            datas.forEach((item) => {
              item.isShow = false
              item.children.forEach((m) => {
                if (m.label == '项目名称') {
                  m.disabled = true
                }
              })
            })
            this.tableCol = datas
            this.tableColOne = []
            this.tableCol.forEach((item) => {
              this.tableColOne.push(...item.children)
            })
            this.colSetupTableCol = datas
          }
        })
    },
    //导出报表
    toExportExcel() {
      if (this.tableList.length == 0) {
        this.$message({
          type: 'warning',
          message: '无数据可导出',
        })
        return false
      }
      let arrval = []
      for (var i = 0; i < this.tableColOne.length; i++) {
        if (this.tableColOne[i].isShow == true) {
          arrval.push(this.tableColOne[i].prop)
        }
      }
      window.location.href =
        common.commonApi +
        'api-s/cs/stats/projectperiod/export?pageNo=1&pageSize=10000' +
        '&areaId=' +
        this.filterField.areaId +
        '&industryId=' +
        this.filterField.industryId +
        '&investment=' +
        this.filterField.investment +
        '&status=' +
        this.filterField.status +
        '&projectName=' +
        this.filterField.projectName +
        '&queryStartDate=' +
        this.filterField.queryStartDate +
        '&queryEndDate=' +
        this.filterField.queryEndDate +
        '&sortField=' +
        this.filterField.sortField +
        '&sort=' +
        this.filterField.sort +
        '&fields=' +
        arrval.join(',') +
        '&access_token=' +
        localStorage.getItem('access_token')
    },
  },
}
</script>
<style lang="less" scoped>
.container {
  .filterBox {
    background: #fff;
    // padding: 24px 0px 0px;
  }
  .mainConBox {
    .baseSearch {
      position: relative;
      padding-left: 102px;
      &Title {
        position: absolute;
        // top: 0;
        left: 0;
        height: 36px;
        line-height: 36px;
        width: 96px;
        text-align: right;
        display: inline-block;
        font-size: 14px;
        color: #606266;
      }
      &Box {
        margin-left: 10px;
      }
    }
  }
  .searchInputWidth .el-input__inner {
    width: 280px;
  }
  .realNameStatisticsBox {
    padding: 24px 24px;
    margin-right: 0px !important;
    background: #fff;
    margin-top: 10px;
    height: 200px;
    .realNameTitle {
      font-size: 22px;
      color: #333;
      margin-bottom: 30px;
    }
  }
  .tableBox {
    padding: 0 24px;
    &Tip {
      height: 68px;
      line-height: 36px;
      font-size: 14px;
      color: #666;
      padding: 16px 0;
      .el-col {
        height: 36px;
        line-height: 36px;
      }
      .colSetupBtn {
        display: inline-block;
        vertical-align: top;
      }
    }
  }
  .tablePage {
    padding: 0 24px;
  }
}
@import '../../../static/css/filterArea.less';
</style>
